package com.ruoyi.web.controller.api;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.constant.WordType;
import com.ruoyi.stu.domain.StuStudentWord;
import com.ruoyi.stu.mapper.StuStudentUnitMapper;
import com.ruoyi.stu.mapper.StuStudentWordMapper;
import com.ruoyi.system.domain.SysStudent;
import com.ruoyi.system.domain.SysWordLearningProgress;
import com.ruoyi.system.domain.SysWordReview;
import com.ruoyi.system.mapper.SysStudentMapper;
import com.ruoyi.system.mapper.SysWordLearningProgressMapper;
import com.ruoyi.system.mapper.SysWordReviewMapper;
import com.ruoyi.system.service.ISysStudentCourseService;
import com.ruoyi.system.service.ISysWordLearningProgressService;

import lombok.AllArgsConstructor;
import lombok.Data;

@RestController
@RequestMapping("/api/v1/unit")
public class ApiUnitController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SysStudentMapper sysStudentMapper;
    @Autowired
    private StuStudentWordMapper stuStudentWordMapper;
    @Autowired
    private StuStudentUnitMapper stuStudentUnitMapper;
    @Autowired
    private SysWordLearningProgressMapper sysWordLearningProgressMapper;
    @Autowired
    private SysWordReviewMapper sysWordReviewMapper;

    @Value("${ruoyi.profile}")
    private String uploadPath;

    @Autowired
    private ISysStudentCourseService sysStudentCourseService;
    @Autowired
    private ISysWordLearningProgressService wordLearningProgressService;

    @GetMapping("/wordList")
    public AjaxResult wordList(
            @RequestParam("courseId") Long courseId,
            @RequestParam("unitId") Long unitId,
            @RequestParam(value = "groupIndex", required = false) Integer groupIndex,
            @RequestParam(value = "type", required = true) String type
            ) {
    	System.out.println("type---" + type);
        // 获取当前登录用户信息
        Long studentId = SecurityUtils.getLoginStudentId();
        
        /*
         *  根据类型返回单词数量
         *  若是单元学习，则扣除学生该单元已学习的数量，并且根据学生的学习设置，返回数量，若已学习总数大等于单元单词总数，则返回所有
         *  若是单元复习，则从当前学生已学习的单词开始，根据最大复习单词数，返回数量
         */
        Integer start = null;
        Integer limit = null;
        if (type == null || type.length() == 0) {
			return AjaxResult.error("类型不能为空");
		} else if (type.equals(WordType.STUDY)) {
			Integer numStudyed = sysWordLearningProgressMapper.sumStudyed(studentId, courseId, unitId, null, null);
			SysStudent sysStudent = sysStudentMapper.selectById(studentId);
			start = numStudyed;
			limit = sysStudent.getWordsPerGroup();
			
			// 计算单元单词总数
			Integer numWordOfUnit = stuStudentWordMapper.count(studentId, unitId, null);
			if (numStudyed >= numWordOfUnit) {
				limit = 99999;
			}
		} else if (type.equals(WordType.DICTATION)) {
			start = 0;
			limit = 99999;
		} else if (type.equals(WordType.WRITING)) {
			start = 0;
			limit = 99999;
		} else if (type.equals(WordType.REVIEW)) {
	    	
	    	String courseName = null;
	    	String unitName = null;
	    	String studentName = null;
			
			List<SysWordReview> listSysWordReview = sysWordReviewMapper.list(studentId, courseId, unitId, 0, 1, "A.id desc", courseName, unitName, studentName);
			Long currentWordId = listSysWordReview != null && listSysWordReview.size() > 0 ? listSysWordReview.get(0).getCurrentWordId() : null;
			SysStudent sysStudent = sysStudentMapper.selectById(studentId);

			// 计算单元单词总数
			Integer numWordOfUnit = stuStudentWordMapper.count(studentId, unitId, null);
			// 根据当前学习的单词ID，获取start
			start = stuStudentWordMapper.count(studentId, unitId, currentWordId);
			if (numWordOfUnit == start) {
				start = 0;
			}
			limit = sysStudent.getMaxReviewWords();
		}

        // 从数据库获取单词列表
        String orderby = "A.word_id asc";
        List<StuStudentWord> listStuStudentWord = stuStudentWordMapper.list(studentId, unitId, start, limit, orderby);
        List<WordInfo> allWordList = new ArrayList<>();
        
        // 转换为WordInfo对象
        for (StuStudentWord word : listStuStudentWord) {
            WordInfo wordInfo = new WordInfo(
            	word.getId(),
                word.getWordName(),
                word.getWordVoiceName(),
                word.getWordVoiceLabel(),
                word.getWordMeaning(),
                1 // 默认难度设为1
            );
            allWordList.add(wordInfo);
        }

        int total = allWordList.size();
        List<WordInfo> resultList;
        int currentGroupIndex = 0;

        // 如果type为unit，直接返回所有单词
        if ("unit".equals(type)) {
            resultList = allWordList;
            AjaxResult result = AjaxResult.success();
            result.put("total", total);
            result.put("data", resultList);
            result.put("groupIndex", 0);
            return result;
        }

        try {
            // 获取每组单词数量
            ResponseEntity<AjaxResult> response = restTemplate.getForEntity(
                "http://localhost:8080/api/course/unit/section/wordCount",
                AjaxResult.class
            );
            
            int sectionWordCount = 10; // 默认每组10个单词
            if (response.getBody() != null && response.getBody().get("sectionWordCount") != null) {
                sectionWordCount = ((Number) response.getBody().get("sectionWordCount")).intValue();
            }

            // 如果是首次查询（没有传groupIndex）
            if (groupIndex == null) {
                // 获取用户的学习进度
                LoginUser loginUser = SecurityUtils.getLoginUser();
                SysWordLearningProgress progress = wordLearningProgressService.list(
                    loginUser.getStudentId(), courseId, unitId);

                if (progress != null && progress.getCurrentWord() != null) {
                    // 查找当前单词在列表中的位置
                    int currentWordIndex = -1;
                    for (int i = 0; i < allWordList.size(); i++) {
                        if (allWordList.get(i).getWord().equals(progress.getCurrentWord())) {
                            currentWordIndex = i;
                            break;
                        }
                    }

                    if (currentWordIndex != -1) {
                        // 计算当前组索引
                        currentGroupIndex = currentWordIndex / sectionWordCount;
                        // 如果当前单词是组内最后一个，移到下一组
                        if ((currentWordIndex + 1) % sectionWordCount == 0) {
                            currentGroupIndex++;
                        }
                    }
                }
            } else {
                currentGroupIndex = groupIndex;
            }

            // 计算当前组的单词范围
            int startIndex = currentGroupIndex * sectionWordCount;
            int endIndex = Math.min(startIndex + sectionWordCount, total);
            
            if (startIndex >= total) {
                resultList = new ArrayList<>();
            } else {
                resultList = allWordList.subList(startIndex, endIndex);
            }

        } catch (Exception e) {
            // 发生异常时使用默认值
            int defaultSectionWordCount = 10;
            int startIndex = (groupIndex != null ? groupIndex : 0) * defaultSectionWordCount;
            int endIndex = Math.min(startIndex + defaultSectionWordCount, total);
            
            if (startIndex >= total) {
                resultList = new ArrayList<>();
            } else {
                resultList = allWordList.subList(startIndex, endIndex);
            }
        }
        
        AjaxResult result = AjaxResult.success();
        result.put("total", total);
        result.put("data", resultList);
        result.put("groupIndex", currentGroupIndex);
        return result;
    }
    
    // 内部类用于表示单词信息
    @Data
    @AllArgsConstructor
    private static class WordInfo {
    	private Long wordId; // 单词ID
        private String word;
        private String phonetic;
        private String syllable;
        private String translation; // 翻译
        private int difficulty; // 难度
    }

    /**
     * 完成复习
     */
    @PostMapping("/finishReview")
    public AjaxResult finishReview(@RequestBody String body)
    {
    	JSONObject bodyJO = JSON.parseObject(body);
    	Long studentId = SecurityUtils.getLoginStudentId();
    	Long courseId = bodyJO.getLong("courseId");
    	Long unitId = bodyJO.getLong("unitId");
    	Long currentWordId = bodyJO.getLong("currentWordId");
    	
    	if (courseId == null) {
			return AjaxResult.error("课程ID不能为空");
		}
    	if (unitId == null) {
			return AjaxResult.error("单元ID不能为空");
		}
    	if (currentWordId == null) {
			return AjaxResult.error("当前复习的单词ID不能为空");
		}
        
    	SysWordReview entity = new SysWordReview();
    	entity.setStudentId(studentId);
    	entity.setCourseId(courseId);
    	entity.setUnitId(unitId);
    	entity.setCurrentWordId(currentWordId);
        int rows = sysWordReviewMapper.insert(entity);
        
        // 更新单元的复习完成状态
        stuStudentUnitMapper.updateStateByStudentIdAndUnitId(studentId, unitId, "state_review", 1);
        
        // 完成课程
        sysStudentCourseService.finishStudentCourse(studentId, courseId);
        return rows > 0 ? AjaxResult.success() : AjaxResult.error("保存学习进度失败");
    }
}